<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletes;
use Ramsey\Uuid\Uuid;
use App\Models\CommentDetail;
use App\Models\User;
use App\Models\Topic;
use App\Models\Attachment;
use App\Models\AttachmentRelationship;
use Illuminate\Support\Str;

class Comment extends Model
{
    use SoftDeletes;

    const ADMIN_TOPIC_SHOW_PER_PAGE = 15;//话题下评论每页数量

    const DETAIL_EXCERPT_WIDTH = 100; //详情摘要宽度

    protected $fillable = [
        'key',
        'uid', 
        'tid',
        'pid', 
        'root_id',
        'is_main_floor',
        'floor_num',
        'comment_count',
        'like_count',
        'dislike_count',
        'favor_count',
        'detail_excerpt',
    ];
    
    protected $touches = ['topic'];

    protected $appends = [];


    public static function booted()
    {
        static::creating(function ($model) {
            $model->key = Uuid::uuid4();
            $model->request_id = REQUEST_ID;
        });

    }


    /**
     * 回复的详情
     * 
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function detail()
    {
        return $this->hasOne(CommentDetail::class, 'cid', 'id');
    }

    /**
     * 回复的隐藏部分
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function hide()
    {
        return $this->hasOne(CommentHide::class, 'cid', 'id');
    }
    
    /**
     * 回复的作者
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function user()
    {
        return $this->hasOne(User::class, 'id', 'uid');
    }
    
    /**
     * 所属话题
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function topic()
    {
        return $this->belongsTo(Topic::class, 'tid', 'id')->withTrashed();
    }

    /**
     * 回复的回复，直属子孙
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function comments()
    {
        return $this->hasMany(__CLASS__, 'pid', 'id');
    }

    /**
     * 回复的全部子孙后代
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function children()
    {
        return $this->hasMany(__CLASS__, 'root_id', 'id');
    }
    
    /**
     * 所属根评论
     */
    public function rootComment()
    {
        return $this->belongsTo(__CLASS__, 'root_id', 'id')->withTrashed();
    }
    
    /**
     * 所属父评论
     */
    public function parentComment()
    {
        return $this->belongsTo(__CLASS__, 'pid', 'id')->withTrashed();
    }

    /**
     * 楼中楼前几楼
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function firstComments()
    {
        return $this->belongsToMany(
            Comment::class,
            CommentComment::TABLE_NAME,
            "root_cid",
            "cid",
            "id",
            "id"
        );
    }
    
    public function likes()
    {
        return $this->morphMany(Like::class, 'target');
    }

}
